import React, {useEffect} from 'react';
import LogFactory from "../../../log/LogFactory";
import {Form, Select} from "antd";
import {SecurityPath} from "../../../type/entity/SecurityPath";
import RequestHandler from "../../../http/RequestHandler";
import {DefaultOptionType} from "rc-select/lib/Select";
import {SecurityMenu} from "../../../type/entity/SecurityMenu";

const log = LogFactory.getLogger("PathSelectHandler");

interface PathOptionType extends DefaultOptionType {
    /**
     * 路径匹配模式
     */
    pattern: string
}

const PathSelectHandler = () => {
    const [ option, setOption ] = React.useState<PathOptionType[]>([]);
    const [ parentPath, setParentPath ] = React.useState<string>("");
    // const form = useForm<SecurityPath>();
    const form = Form.useFormInstance<SecurityMenu>();

    useEffect(() => {
        RequestHandler.get<SecurityPath[]>("/manager/admin/path/list/not-last")
            .then(res => {
                log.debug("获取所有未最后的路径列表:", res.data);
                if (res.success){
                    const pid = form.getFieldValue("parentId");
                    const pattern = form.getFieldValue("pattern");
                    setOption(res.data.map(item => {
                        if (pid === item.id){
                            setParentPath(item.pattern);
                            !pattern && form.setFieldValue("pattern", item.pattern.replaceAll("*", ""));
                        }
                        return {
                            label: item.explain,
                            value: item.id,
                            pattern: item.pattern
                        };
                    }));
                }
            });
    }, []);

    const onChange = (value: string, op: PathOptionType | PathOptionType[]) => {
        setParentPath((op as PathOptionType).pattern);
        form.setFieldValue("pattern", (op as PathOptionType).pattern.replaceAll("*", ""));
    };

    return (
           <Form.Item<SecurityPath> name={"parentId"} label={"父路径"} tooltip={parentPath}>
               <Select
                   onChange={onChange}
                   placeholder={"请选择父路径"}
                   allowClear
                   options={option}
                   loading={option.length === 0}

               />
           </Form.Item>
    );
};

export default PathSelectHandler;